var app = getApp();
var WxParse = require('../../../../lib/wxParse/wxParse.js');
var util = require('../../../../utils/util.js');
var api = require('../../../../config/api.js');
var user = require('../../../../utils/user.js');
const dianpu = require('../../../../utils/common/dianpu.js');
const draw = require('../../../../utils/common/drawhaibao.js');

var lastTime = null;

Page({
  data: {
    id: '',
    groupbuying: {},
    goods: {},
    lunbotu: [],
    canshu: [],
    tuijianGoods: [],
    number: 1,
    lowbuynum: 1,
    hadgroupbuynum: 0,
    opendgg: false,
    openShare: false,
    openTwocodeimg: false,
    shareImage: '',
    canWrite: false, //用户是否获取了保存相册的权限
    timeout: false,
    shouqing: false,
    isgroupbuying: true,
    fukucunsale: true, //true为允许负库存销售；false为不允许
    endTime: '3000-01-01 00:00:00',
    day: '00',
    hour: '00',
    minute: '00',
    second: '00',
    webstore: '',
    template: {},
    image: "",
    zhutu: "",
    twoCodeUrl: "",
    shareUserId: '',
    page: 1,
    limit: 10
  },

  // 获取商品信息
  getGoodsInfo: function () {
    let that = this;
    util.request(api.GroupbuyingGoodsDetail, {
      id: that.data.id
    }).then(function (res) {
      if (res) {
        if (res.result == 1) {
          var _canshu = [];
          var _lunbotu = [];
          if (res.data.goods.canshuList.length > 0) {
            _canshu = JSON.parse(res.data.goods.canshuList);
          }
          if (res.data.goods.lunbotu.length > 0) {
            _lunbotu = JSON.parse(res.data.goods.lunbotu);
          }
          that.setData({
            groupbuying: res.data.groupbuying,
            goods: res.data.goods,
            fukucunsale: res.data.fukucunsale,
            endTime: res.data.groupbuying.endTime,
            number: res.data.groupbuying.lowbuynum,
            lowbuynum: res.data.groupbuying.lowbuynum,
            hadgroupbuynum: res.data.groupbuying.hadgroupbuynum,
            lunbotu: _lunbotu,
            canshu: _canshu,
            ggname: res.data.goods.ggname
          });
          if (res.data.goods.kucun < that.data.number) {
            that.setData({
              shouqing: true
            });
          }
          WxParse.wxParse('goodsDetail', 'html', res.data.goods.xiangxijieshao, that);
          //获取推荐商品
          that.getGoodsTuijian();
        }
      }
    });
  },

  // 获取推荐商品
  getGoodsTuijian: function () {
    let that = this;
    util.request(api.GoodsTuijian, {
      "id": that.data.goods.id,
      "page": that.data.page,
      "limit": that.data.limit
    }).then(function (res) {
      if (res.result == 1) {
        if (res.data.length > 0) {
          that.setData({
            tuijianGoods: that.data.tuijianGoods.concat(res.data),
            page: that.data.page + 1
          });
        } else {
          wx.showToast({
            title: '已经被您看完了!',
            icon: 'none',
            duration: 2000
          });
          return false;
        }
      }
    });
  },

  //立即购买（先自动加入购物车）
  buyadd: function () {
    var that = this;
    if (this.data.opendgg == false) {
      //打开规格选择窗口
      this.setData({
        opendgg: !this.data.opendgg
      });
    } else {
      util.jhxLoadShow("加载中...");
      let nowTime = +new Date();
      if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
        lastTime = nowTime;
      } else {
        return false;
      }
      //立即购买
      util.request(api.MarketingShoppingCartBuyAdd, {
          number: this.data.number,
          price: that.data.groupbuying.groupprice,
          pk_marketing: that.data.id,
          tablename: "mt_groupbuying",
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            // 如果storage中设置了shoppingcartid，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            wx.navigateTo({
              url: '/pages/marketing/mtorder/mtorder'
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },

  cutNumber: function () {
    let that = this;
    if (that.data.number > that.data.lowbuynum) {
      this.setData({
        number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
      });
    } else {
      this.setData({
        number: that.data.lowbuynum
      });
    }
  },

  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },

  switchdgg: function () {
    if (this.data.opendgg == false) {
      this.setData({
        opendgg: !this.data.opendgg
      });
    }
  },

  closedgg: function () {
    this.setData({
      opendgg: false,
    });
  },


  openCartPage: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/shoppingcart'
    });
  },

  // 页面分享
  onShareAppMessage: function () {
    let that = this;
    let memberUserid = wx.getStorageSync('memberUserid');
    return {
      title: that.data.goods.goodsname,
      desc: '好东西要一起分享！',
      path: '/pages/marketing/groupbuying/groupbuyingDetail/groupbuyingDetail?id=' + that.data.id + '&shareMemberUserid=' + memberUserid
    }
  },

  shareFriendOrCircle: function () {
    let that = this;
    if (that.data.openShare === false) {
      this.setData({
        openShare: !this.data.openShare
      });
    } else {
      return false;
    }
  },

  handleSetting: function (e) {
    var that = this;
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '不授权无法保存',
        showCancel: false
      })
      that.setData({
        canWrite: false
      })
    } else {
      wx.showToast({
        title: '保存成功'
      })
      that.setData({
        canWrite: true
      })
    }
  },

  closeShare: function () {
    this.setData({
      openShare: false,
    });
    wx.hideLoading()
  },

  closetwocodeimg: function () {
    this.setData({
      openTwocodeimg: false,
    });
    wx.hideLoading()
  },

  // 生成成功
  canvasSuc(e) {
    wx.hideLoading()
    this.setData({
      image: e.detail.path
    })
  },

  // 点击保存海报弹出展示海报图片窗口
  getSave() {
    let that = this;
    that.setData({
      openShare: false
    });
    wx.showLoading({
      title: '正在努力生成中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000);
    var scene = {
      "page": "groupbuyingDetail",
      "page_data_id": that.data.id
    };
    util.request(api.CreateQcodeImg, {
      scene: JSON.stringify(scene)
    }, 'GET').then(function (res) {
      that.setData({
        twoCodeUrl: res.data
      });
      wx.getSetting({
        success: function (res) {
          //不存在相册授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function () {
                var drawtemplate = draw.getMarketingDraw(that.data.goods.zhutu, that.data.groupbuying.groupprice,that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
                that.setData({
                  canWrite: true,
                  template: drawtemplate
                })
              },
              fail: function (err) {
                // 授权失败
                wx.showModal({
                  title: '警告',
                  content: '您点击了拒绝授权,将无法正常保存图片,点击确定重新获取授权。',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          console.log('授权成功')
                        }
                      })
                    }
                  }
                })
              }
            })
          } else {
            var drawtemplate = draw.getMarketingDraw(that.data.goods.zhutu,that.data.groupbuying.groupprice, that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
            that.setData({
              canWrite: true,
              openTwocodeimg: true,
              template: drawtemplate
            });
          }
        }
      })
    });
  },

  //保存海报
  savehaibao: function () {
    let that = this;
    wx.getSetting({
      success: (set) => {
        wx.saveImageToPhotosAlbum({
          filePath: that.data.image,
          success: (res) => {
            if (res.errMsg == "saveImageToPhotosAlbum:ok") {
              wx.showModal({
                title: '存图成功',
                content: '图片成功保存到相册了，可以分享到朋友圈了',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#a78845',
                success: function (res) {
                  if (res.confirm) {}
                }
              })
            }
          }
        })
        if (set.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting()
        }
      }
    })
  },


  previewImg() {
    wx.previewImage({
      current: this.data.image,
      urls: [this.data.image]
    })
  },

  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },

  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let that = this;
    if (options.id) {
      that.setData({
        id: options.id
      });
    }
    if (options.shareMemberUserid) {
      //这个shareMemberUserid的存在证明是通过分享页面进来的
      util.request(api.Yemianfenxiang, {
        shareMemberUserid: options.shareMemberUserid,
        page_data_id: options.id,
        page: 'groupbuyingDetail'
      }, 'GET').then(function (res) {
        if (res.result == 1) {

        }
      });
    }
  },
  onShow: function () {
    // 页面显示
    var that = this;
    if (Object.keys(that.data.goods).length == 0) {
      that.getGoodsInfo();
      that.countTime()
    }
  },

  // 下拉刷新
  onReachBottom() {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    if (that.data.tuijianGoods.length > 0) {
      that.getGoodsTuijian();
    }
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  //点击电话图标
  tel: function () {
    dianpu.getmendiantel().then(res => {
      wx.makePhoneCall({
        phoneNumber: res.lianxirenmobile,
      })
    }).catch(() => {
      wx.showToast({
        title: '获取联系方式失败!',
        icon: 'none',
        duration: 2000
      });
    });
  },
  //倒计时
  countTime: function () {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endTime); //设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差               
    var day, hour, minute, second;
    if (leftTime >= 0) {
      day = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      hour = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      minute = Math.floor(leftTime / 1000 / 60 % 60);
      second = Math.floor(leftTime / 1000 % 60);
      second = second < 10 ? "0" + second : second
      minute = minute < 10 ? "0" + minute : minute
      hour = hour < 10 ? "0" + hour : hour
      that.setData({
        hour: hour,
        minute: minute,
        second: second
      })
      if (day >= 99) {
        that.setData({
          day: 99
        })
      } else {
        that.setData({
          day: day
        })
      }
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        timeout: true
      })
    }
  }
})